package com.xhwy.controller;

import com.xhwy.entity.User;
import com.xhwy.mapper.UserMapper;
import com.xhwy.param.UserCheckParam;
import com.xhwy.param.UserLoginParam;
import com.xhwy.param.UserParam;
import com.xhwy.param.UserUpdateParam;
import com.xhwy.service.UserService;
import com.xhwy.util.PageUtil;
import com.xhwy.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 分页查询
     *
     * @param user 筛选条件
     * @param pageUtil 分页对象
     * @return 查询结果
     */
    @GetMapping
    public PageUtil<User> queryAllUsersByLimit(User user, PageUtil<User> pageUtil){
        return userService.queryAllUsersByLimit(user, pageUtil);
    }

    @PutMapping("/{userId}/state/{isLock}")
    public R updateUserState(@PathVariable("userId") Integer userId, @PathVariable("isLock") boolean isLock){
        return userService.updateUserState(userId, isLock);
    }

    @PostMapping
    public R addUser(@RequestBody @Validated User user, BindingResult result) {
        if (result.hasErrors()) return R.fail("请求参数异常!");
        return userService.addUser(user);
    }

    @PutMapping
    public R updateUser(@RequestBody @Validated UserUpdateParam userUpdateParam, BindingResult result){
        if (result.hasErrors()) return R.fail("请求参数异常！");
        return userService.updateUser(userUpdateParam);
    }

    @DeleteMapping("/{userId}")
    public R deleteUserByUserId(@PathVariable("userId") Integer userId){
        return userService.deleteUserByUserId(userId);
    }

    /**
     * 检查账号是否可用
     * @param userCheckParam 接收检查的账号实体，内部有参数校验注解
     * @param result 获取校验结果的实体对象
     * @return 返回封装
     */
    @PostMapping("check")
    public R check(@RequestBody @Validated UserCheckParam userCheckParam, BindingResult result) {

        //检查是否符合校验注解的规则     符合false 不符合true
        boolean b = result.hasErrors();
        if(b)
            return R.fail("账号为空，不可使用");

        return userService.check(userCheckParam);
    }

    @PostMapping("register")
    public R register(@RequestBody @Validated UserParam userParam, BindingResult result){
        if (result.hasErrors()){
            //校验不通过
            return R.fail("参数错误，不可注册");
        }
        return userService.register(userParam);
    }

    @PostMapping("login")
    public R login(@RequestBody @Validated UserLoginParam userLoginParam, BindingResult result){
        if(result.hasErrors()) {
            return R.fail("参数异常，无法登录");
        }

        return userService.login(userLoginParam);
    }
}
